package com.dunqi.gpm.shunqing.home.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dunqi.gpm.shunqing.R;
import com.dunqi.gpm.shunqing.common.api.ApiFactory;
import com.dunqi.gpm.shunqing.common.api.RxSchedulers;
import com.dunqi.gpm.shunqing.common.base.BaseFragment;
import com.dunqi.gpm.shunqing.common.base.ComObserver;
import com.dunqi.gpm.shunqing.common.base.Data;
import com.dunqi.gpm.shunqing.common.base.FragmentCallBack;
import com.dunqi.gpm.shunqing.common.util.LogUtils;
import com.dunqi.gpm.shunqing.common.util.SwipeUtil;
import com.dunqi.gpm.shunqing.home.activity.ProjectDetailActivity;
import com.dunqi.gpm.shunqing.home.activity.ProjectTimelineActivity;
import com.dunqi.gpm.shunqing.home.adapter.HomeProjectAdapter;
import com.dunqi.gpm.shunqing.home.bean.Page;
import com.dunqi.gpm.shunqing.home.bean.Project;
import com.dunqi.gpm.shunqing.home.constance.Constance;
import com.dunqi.gpm.shunqing.home.eventbus.FinishAndRefresh;
import com.dunqi.gpm.shunqing.home.widget.EmptyView;
import com.dunqi.gpm.shunqing.my.util.UserUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.vov.vitamio.utils.Log;

/**
 * Created by 空 on 2017/11/17 0017.
 */

public class ProjectListFragment extends BaseFragment implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    ArrayList<Project> data_static = new ArrayList<>();
    private static final String DATA = "data";
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;
    ArrayList<Project> data = new ArrayList<>();
    private HomeProjectAdapter adapter;
    private HashMap<String, String> params;
    private int type;

    @Override
    protected void refreshData(Bundle savedInstanceState) {

        net();
    }

    FragmentCallBack callBack;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof FragmentCallBack) {
            callBack = (FragmentCallBack) context;
        } else {
            throw new RuntimeException("Activity 需要实现 FragmentCallBack 接口");
        }
    }

    private void net() {
        params.put(Constance.PAGE, String.valueOf(page));
        ApiFactory.getInstance()
                .selectProjects(params)
                .compose(RxSchedulers.<Data<Page<Project>>>io_main())
                .subscribe(new ComObserver<Page<Project>>() {
                    @Override
                    public void onSuccess(Page<Project> projectPage) {
                        ArrayList<Project> list = projectPage.getList();

                        if (page == 1) {
                            data.clear();
                            data_static.clear();
                        }

                        data.addAll(list);
                        data_static.addAll(list);
                        page++;
                        adapter.notifyDataSetChanged();

                        if (projectPage.isHasNextPage()) {
                            adapter.loadMoreComplete();
                        } else {
                            adapter.loadMoreEnd(true);
//                            return;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        adapter.loadMoreFail();
                    }

                    @Override
                    public void onFinal() {
                        swipeRefresh.setRefreshing(false);
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposables(d);
                    }
                });
    }

    @Override
    protected void initUiAndListener() {
        EventBus.getDefault().register(this);
        SwipeUtil.init(swipeRefresh);

        recycler.setLayoutManager(new LinearLayoutManager(context));
        adapter = new HomeProjectAdapter(data);
        recycler.setAdapter(adapter);
        adapter.setEmptyView(new EmptyView(context));
        adapter.setOnItemClickListener(this);
        adapter.setEmptyView(new EmptyView(context));

        adapter.setOnLoadMoreListener(this, recycler);
        swipeRefresh.setOnRefreshListener(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_project_list;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Project project = data.get(position);
        int homeMenuId = HomeFragment.homeMenuId;
        if (homeMenuId == Constance.MENU_DIVIDED_PROJECT ||
                homeMenuId == Constance.MENU_QUERY_PROJECT ||
                homeMenuId == Constance.MENU_MY_ATTENTION) {
            ProjectTimelineActivity.start(context, project);
        } else {
            ProjectDetailActivity.start(context, project, 0);
        }
    }

    public static ProjectListFragment newInstance(HashMap<String, String> params, int type) {
        ProjectListFragment projectListFragment = new ProjectListFragment();
        Bundle bundle = new Bundle();
        if (UserUtil.userFromRespOrg()) {
            params.put("uda", String.valueOf(true));
        } else {
            params.put("uda", String.valueOf(false));
        }

        bundle.putInt(Constance.TYPE, type);
        bundle.putSerializable(DATA, params);
        projectListFragment.setArguments(bundle);
        return projectListFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (arguments != null) {
            params = (HashMap<String, String>) arguments.getSerializable(DATA);
            type = arguments.getInt(Constance.TYPE);
            params.put(Constance.PAGE, String.valueOf(page));
//            params.put("enabled", String.valueOf(1));
        }
    }

    @Subscribe
    public void onEventMainThread(FinishAndRefresh finishAndRefresh) {
        onRefresh();
        EventBus.getDefault().removeStickyEvent(finishAndRefresh);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void action(EvnetbusMSG messageEvent) {
//        Toast.makeText(getActivity(), messageEvent.type, Toast.LENGTH_SHORT).show();
        //                        "projectConstructionModeText":"重点项目",
        String type = messageEvent.type;
        if (data == null) data = new ArrayList<>();
        data.clear();
        if ("all".equals(type)) {
            data.addAll(data_static);
        } else {
            for (Project p : data_static) {
                if (type.equals(p.getImportantTypeText())) {
                    data.add(p);
                }
            }
        }
        // LogUtils.w("changed", data_static.size() + " ---- " + data.size());
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onLoadMoreRequested() {
        net();
    }

    @Override
    public void onRefresh() {
        page = 1;
        net();
        callBack.callBackkUri(Uri.parse("refresh://全部项目"));
    }

    public static class EvnetbusMSG {
        String type;

        public EvnetbusMSG(String type) {
            this.type = type;
        }
    }
}
